<script setup lang="ts">
import { addUserApi, editUserAPI, getRoleDetailAPI, getTreeListAPI } from '@/apis/system';
import type { RoleData, RoleItemParams } from '@/types/system';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import type { TreeInstance } from 'element-plus/lib/components/index.js';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute()
const router = useRouter()

// 分段器控制逻辑 ---------------------------
const activeIndex = ref<number>(1) // 分段器索引
// 分段器索引加
const activeJia = async () => {
  await roleFormRef.value?.validate()// 验证表单
  if (activeIndex.value >= 3) return // 判断是否是最后一步
  // 判断是否是第二步并且没有选择任何权限
  if (activeIndex.value === 2 && roleFormParams.value.perms.flat().length === 0) return ElMessage.error('请至少选择一个权限')
  // 下一步
  activeIndex.value++
}
// 分段器索引减
const activeJian = () => {
  if (activeIndex.value <= 1) return
  activeIndex.value--
}
// 表单实例
const roleFormRef = ref<FormInstance>()
// 添加角色所需参数 ---------------------------------
const roleFormParams = ref<RoleItemParams>({
  roleName: '', // 角色名称
  remark: '', // 角色描述
  perms: [] // 权限信息
})
// 表单校验
const roleFormRules = ref<FormRules<RoleItemParams>>({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
})

// 获取权限列表 -----------
const treeList = ref<RoleData[]>([])
// 获取权限列表函数
const getTreeList = async () => {
  const res = await getTreeListAPI()
  treeList.value = res.data
}
getTreeList()

// 获取选中的节点 ---------------------------------
const treeRefs = ref<TreeInstance[]>() // 设置的树节点实例
const diabledTreeRefs = ref<TreeInstance[]>() // 查看的树节点实例
// 节点change事件
const changeTree = () => {
  // 每次调用清空perms数组
  roleFormParams.value.perms = []
  // 循环每一个树节点获取 选中的节点追加到perms里
  treeRefs.value?.forEach((item: TreeInstance, index: number) => {
    // 这里因为我定义的类型原因，每一项必须是个数字，而树节点返回给我的是个number数组， 所以需要map一下把每一项转化类型
    roleFormParams.value.perms.push(item.getCheckedKeys().map(num => +num)) // 获取选中的节点 getCheckedKeys()
    // 设置查看的树节点选中的节点
    diabledTreeRefs.value![index].setCheckedKeys(item.getCheckedKeys())
  })
}

// 添加角色函数 --------------------------
const addRoleUser = async () => {
  await addUserApi(roleFormParams.value) // 添加角色发请求
  ElMessage.success('添加成功') // 提示
  router.back() // 返回
}

// 编辑业务逻辑 -----------------------------------------
// 获取角色详情
const getRoleDetail = async () => {
  const res = await getRoleDetailAPI(+route.params.id) // 获取角色详情
  // 回显数据
  roleFormParams.value.perms = res.data.perms
  roleFormParams.value.roleName = res.data.roleName
  roleFormParams.value.remark = res.data.remark
}
// 判断是否是编辑业务逻辑
if (route.params.id) {
  getRoleDetail()
}

// 编辑角色函数
const editRoleUser = async () => {
  // 忘传ID了！  艸
  await editUserAPI(roleFormParams.value, +route.params.id)
  ElMessage.success('编辑成功')
  router.back()
}
</script>

<template>
  <div class="add-role">
    <header class="add-header">
      <el-page-header :content="$route.params.id ? '编辑角色' : '添加角色'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <!-- 分段器 -->
      <div class="step-container">
        <el-steps direction="vertical" :active="activeIndex">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <!-- 角色信息 -->
      <div class="form-container" v-show="activeIndex === 1">
        <div class="title">角色信息</div>
        <el-form ref="roleFormRef" class="form-box" :model="roleFormParams" :rules="roleFormRules">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleFormParams.roleName" />
          </el-form-item>
          <el-form-item label="角色描述" prop="remark">
            <el-input v-model="roleFormParams.remark" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
      <!-- 权限信息 -->
      <div class="form-container" v-show="activeIndex === 2">
        <div class="title">权限配置</div>
        <div class="tree-wrapper">
          <div v-for="(item, index) in treeList" :key="item.id" class="tree-item">
          <div class="tree-title"> {{ item.title }} </div>
          <el-tree
            :data="item.children"
            :props="{ label: 'title', disabled: () => false}"
            show-checkbox
            default-expand-all
            node-key="id"
            :default-checked-keys="roleFormParams.perms[index]"
            @check="changeTree"
            ref="treeRefs"
          /></div>
        </div>
      </div>
      <!-- 检查 -->
      <div class="form-container" v-show="activeIndex === 3">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleFormParams.roleName }}</div>
            <div class="form-item">角色描述：{{ roleFormParams.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="(item, index) in treeList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="diabledTreeRefs"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :default-checked-keys="roleFormParams.perms[index]"
                  :props="{ label: 'title', disabled: () => true }"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="activeIndex > 1" @click="activeJian">上一步</el-button>
        <el-button v-if="activeIndex < 3" type="primary" @click="activeJia">下一步</el-button>
        <template v-else>
          <el-button v-if="!$route.params.id" type="primary" @click="addRoleUser">确认添加</el-button>
          <el-button v-else type="primary" @click="editRoleUser">确认修改</el-button>
        </template>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px 5px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 0.5;
      height: 100%;
      background-color: #fff;
      overflow-y: auto;
      padding: 0 40px;
      margin: 0 auto;
      transform: translateX(-50px);
      .title {
        // height: 60px;
        // line-height: 60px;
        margin: 20px 0 30px;
        padding-left: 20px;
        transform: translateX(-50px);
        border-left: 4px solid #4770ff;
      }

      .form {
        margin-bottom: 20px;
        // padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>